<script setup lang='ts'>
import type { ElTree } from 'element-plus'
import type { VxePagerEvents } from 'vxe-table'

import { useGetDataSourceUserListByPage, useGetOrgDataSourceTree } from '@fl/api/man-api'
import { SearchForm, SearchTable } from '@fl/components'
import { getElementLabelLine } from 'element-tree-line'
import 'element-tree-line/dist/style.css'
import { cloneDeep } from 'lodash-es'
import { h } from 'vue'

import { WHCJSOURCE_DICT } from './constant'

const emit = defineEmits(['transfer'])

const ElementTreeLine = getElementLabelLine(h)

type Tree = {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
    children: 'childs',
    label: 'orgName',
    value: 'orgCode',
}
watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

function filterNode(value: string, data: Tree) {
    if (!value)
        return true
    return data.orgName.includes(value)
}

const initialState = {
    xm: '',
}

const state = ref(cloneDeep(initialState))

const columns = [
    {
        colProps: {
            span: 12,
        },
        label: '姓名',
        prop: 'xm',
        renderField: (_, onChange) => {
            return h(ElInput, {
                onChange,
                onKeydown: (event: any) => {
                    if (event.key === 'Enter') {
                        event.preventDefault()
                    }
                },
            })
        },
        valueType: 'Input',
    },
]

const gridOptions = reactive({
    columns: [
        { fixed: 'left', title: '序号', type: 'seq', width: 50 },
        { field: 'personxm', title: '姓名' },
        { field: 'personsszzname', title: '所属组织' },
        { field: 'personsjhm', title: '手机号码', width: 150 },
        { field: 'personxgr', title: '修改人' },
        { field: 'personxgsj', title: '修改时间' },
        { field: 'personryzt', title: '人员状态' },
        { fixed: 'right', slots: { default: 'opreate' }, title: '操作' },
    ],
    data: [{}],
    height: 700,
    rowConfig: {
        keyField: 'whcjpersonid',
    },
    showOverflow: true,
})

const initialPage = { currentPage: 1, pageSize: 10, total: 0 }

const tablePage = ref(cloneDeep(initialPage))

const visible = defineModel<boolean>('visible', { required: true })

const dialog = '选择人员'

const formRef = ref()

const bm = ref('')

const params = computed(() => {
    return {
        bm: bm.value,
        page: tablePage.value.currentPage,
        size: tablePage.value.pageSize,
        xm: state.value.xm,
    }
})

const { data: SourceTreeData, isLoading: SourceTreeLoading } = useGetOrgDataSourceTree()

const { data: UserListData, isLoading: UserListLoading } = useGetDataSourceUserListByPage(params)

const tableData = computed(() => {
    if (UserListData.value) {
        const result = cloneDeep(UserListData.value?.records) || []
        result.forEach((item: any) => {
            if (item.whcjsource) {
                item.whcjsourceName = WHCJSOURCE_DICT[item.whcjsource]
            }
        })
        return result
    }
    return []
})

const treeData = computed(() => SourceTreeData.value ? cloneDeep(SourceTreeData.value) : [])

const loading = computed(() => SourceTreeLoading.value)

function cancel() {
    visible.value = false
}

function reset() {
    state.value = initialState
}

function handleNodeClick(data: Tree) {
    tablePage.value.currentPage = 1
    bm.value = data.orgCode
}

function search(val: any) {
    tablePage.value.currentPage = 1
    state.value = cloneDeep(val)
}

function resetSearchForm() {
    tablePage.value.currentPage = 1
    state.value = initialState
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function selectValue(val: any) {
    emit('transfer', val)
    cancel()
}

watchEffect(() => {
    if (UserListData.value) {
        tablePage.value.total = UserListData.value?.total ?? 0
    }
})
watchEffect(() => {
    if (SourceTreeData.value && visible.value) {
        console.log(111)

        const orgCode = SourceTreeData.value?.[0]?.orgCode
        setTimeout(() => {
            treeRef.value?.setCurrentKey(orgCode)
            bm.value = orgCode
        }, 100)
    }
})

const asideWidth = ref<number>(300)

let isResizing = false
let startX = 0
let startWidth = 0

function startResizing(event: MouseEvent) {
    isResizing = true
    startX = event.clientX
    startWidth = asideWidth.value

    document.addEventListener('mousemove', resizeAside)
    document.addEventListener('mouseup', stopResizing)
}

function resizeAside(event: MouseEvent) {
    if (isResizing) {
        const newWidth = startWidth + (event.clientX - startX)
        asideWidth.value = newWidth < 300 ? 300 : newWidth > 500 ? 500 : newWidth // 设置最小宽度为 50px
    }
}

function stopResizing() {
    isResizing = false
    document.removeEventListener('mousemove', resizeAside)
    document.removeEventListener('mouseup', stopResizing)
}

onMounted(() => {
    document.addEventListener('mouseup', stopResizing)
})

onUnmounted(() => {
    document.removeEventListener('mouseup', stopResizing)
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialog"
                width="1100"
                :has-footer="false"
                fullscreen
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="loading"
                    animated
        />

        <el-container v-else
                      class="h-900 overflow-y-auto"
        >
            <el-aside class="p-10 mr-10 bg-#fff relative"
                      :style="{ width: `${asideWidth}px` }"
            >
                <div class="flex flex-col h-full">
                    <el-input v-model="filterText"
                              placeholder="请输入关键字"
                              class="mb-10"
                    />

                    <ElTreeV2 ref="treeRef"
                              :data="treeData"
                              :props="defaultProps"
                              highlight-current
                              :filter-method="filterNode"
                              :expand-on-click-node="false"
                              :height="800"
                              @node-click="handleNodeClick"
                    >
                        <template #default="{ node }">
                            <ElementTreeLine :node="node"
                                             :tree-data="treeData"
                                             :show-label-line="true"
                            >
                                <span :title="node.label"
                                      v-text="node.label"
                                />
                            </ElementTreeLine>
                        </template>
                    </ElTreeV2>

                    <div class="resizer"
                         @mousedown="startResizing"
                    />
                </div>
            </el-aside>

            <el-main class="bg-#fff">
                <div class="flex flex-col gap-20 h-full">
                    <div class="text-16 font-700">
                        人员列表
                    </div>

                    <SearchForm v-bind="state"
                                ref="formRef"
                                :columns="columns"
                                submit-text="查询"
                                class="mb-20"
                                :label-width="60"
                                @submit="search"
                                @reset="resetSearchForm"
                    />

                    <SearchTable v-bind="gridOptions"
                                 v-model:pager="tablePage"
                                 class="flex-1"
                                 :loading="UserListLoading"
                                 :data="tableData"
                                 @page-change="handlePageChange"
                    >
                        <template #opreate="{ row }">
                            <el-button text
                                       :disabled="row.whcjsyn !== '0'"
                                       @click="selectValue(row)"
                            >
                                {{ row.whcjsyn === '0' ? '选择' : '已同步' }}
                            </el-button>
                        </template>
                    </SearchTable>

                <!-- <div class="bg-red flex-1 h-full" /> -->
                </div>
            </el-main>
        </el-container>
    </PlusDialog>
</template>

<style lang="scss" scoped>
.resizer {
    position: absolute;
    top: 0;
    right: 0;
    width: 3px;
    height: 100%;
    cursor: ew-resize;
    background-color: rgb(0 0 0 / 20%);
}

:deep(.el-tree-node:last-child > .el-tree-node__content::before) {
    content: '';
    width: 0;
    height: 10000px;
    background-color: #e7e7e7;
    position: absolute;
    margin-left: -9px;
    bottom: 13px;
}
</style>
